# -*- coding: windows-1251 -*-

from ZSI.ServiceContainer import ServiceContainer, SOAPRequestHandler
from OpenSSL import SSL
import socket, os, sys, thread
from services.SOAPServicesAgent import HomebuhWebService, WSRequestHandler

LISTEN_HOST='localhost'
LISTEN_PORT=8443

KEYFILE=os.path.join(sys.path[0], "resources/auth/ssl/server.key")
CERTFILE=os.path.join(sys.path[0], "resources/auth/ssl/server.crt")

class SecureServiceContainer(ServiceContainer):
    
    def __init__(self, serverAddress, handlerClass, services):
        ServiceContainer.__init__(self, serverAddress, services=services, RequestHandlerClass=handlerClass)
        self.proto = "https"
        
        context = SSL.Context(SSL.SSLv23_METHOD)
        context.use_privatekey_file(KEYFILE)
        context.use_certificate_file(CERTFILE)
        
        self.socket = SSL.Connection(context, socket.socket(self.address_family, self.socket_type))
        self.server_bind()
        self.server_activate()
        
class SecureWSRequestHandler(WSRequestHandler):
    
    def setup(self):
        self.connection = self.request
        self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
        self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
        
if (__name__ == "__main__"):
    serverAddress = (LISTEN_HOST, LISTEN_PORT)
    server = SecureServiceContainer(serverAddress, handlerClass=SecureWSRequestHandler, services=[HomebuhWebService()])
    
    server.serve_forever()